package com.mall.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.pojo.Category;
import com.mall.pojo.Wares;
import com.mall.service.ICategoryService;
import com.mall.service.IWaresService;
import com.mall.utils.R;
import com.mall.vo.AddCategoryVo;
import com.mall.vo.CategoryVo;
import com.mall.vo.SearchCategoryVo;
import com.mall.vo.WareVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品分类管理
 *
 * @author cxx
 * @date 2023/4/25 16:09
 */
@Slf4j
@RestController
@RequestMapping("/category")
@SaCheckLogin
public class CategoryController {
    @Resource
    private ICategoryService categoryService;
    @Resource
    private IWaresService waresService;

    /**
     * 获取树形级别分类以及类下商品
     *
     * @param
     * @return com.mall.utils.R<java.util.List < com.mall.DTO.CategoryDTO>>
     * @author cxx
     * @date 2023/6/1 10:39
     */
    @GetMapping("/cate")
    @Cacheable(value = "Category", unless = "#result.data.size()==0")
    public R<List<SearchCategoryVo>> listCategoryWithTree() {
        List<SearchCategoryVo> categoryVos = categoryService.listCategoryWithTree();

        return R.success(categoryVos);
    }

    /**
     * 跟据type获取商品分类列表，type分为1，2，3级,type需要前端传递
     *
     * @param type 分类级别
     * @return com.mall.utils.R<java.util.List < CategoryVo>>
     * @author cxx
     * @date 2023/6/11 18:57
     */
    @GetMapping("/get")
    public R<List<CategoryVo>> get(@RequestParam(name = "type") Integer type) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getType, type);
        List<Category> list = categoryService.list(queryWrapper);
        List<CategoryVo> collect = list.stream().map(item -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(item, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());
        return ObjectUtils.isNotEmpty(collect) ? R.success(collect) : R.error("该type没有商品分类", collect);
    }

    /**
     * 根据分类id获取该类下所有的商品，页码，页大小可以不用传递，不传递则是默认的1和5
     *
     * @param categoryId 分类id
     * @param page       页码
     * @param pageSize   页大小
     * @return com.mall.utils.R<java.util.List < com.mall.pojo.Wares>>
     * @author cxx
     * @date 2023/6/7 21:37
     */
    @GetMapping("/getWareByClass")
    public R<Object> getWareByClass(@RequestParam(name = "categoryId") String categoryId, @RequestParam(name = "page", required = false, defaultValue = "1") Integer page, @RequestParam(name = "pageSize", required = false, defaultValue = "5") Integer pageSize) {
        Page<Wares> warePage = categoryService.getWaresByCategory(categoryId, page, pageSize);
        List<WareVo> collect = null;

        if (warePage.getRecords().size() > 0) {
            collect = warePage.getRecords().stream().map(item -> {
                WareVo wareVo = new WareVo();
                BeanUtils.copyProperties(item, wareVo);
                return wareVo;
            }).collect(Collectors.toList());
            return R.success(collect);
        }

        return R.error("该类别下没有商品");


    }

    /**
     * 管理员添加一个商品分类
     *
     * @param aClass 新加分类的名字和它上级分类的名字
     * @return com.mall.utils.R<java.lang.String>
     * @author cxx
     * @date 2023/4/25 22:48
     */
    @SaCheckRole(value = {"admin", "super-admin"}, mode = SaMode.OR)
    @CacheEvict(value = "Category", allEntries = true)
    @PostMapping("/add")
    public R<String> add(@RequestBody AddCategoryVo aClass) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getName, aClass.getParentName());
        List<Category> list = categoryService.list(wrapper);
        Category category = new Category();
        category.setType(3);
        category.setName(aClass.getName());
        category.setParentId(list.get(0).getId());
        boolean b = categoryService.save(category);
        return b ? R.success("添加分类成功!") : R.error("添加分类失败!");
    }

    /**
     * 删除一个分类
     *
     * @param classId 要删除的分类的id
     * @return com.mall.utils.R<java.lang.String>
     * @author cxx
     * @date 2023/4/26 20:59
     */
    @SaCheckRole(value = {"admin", "super-admin"}, mode = SaMode.OR)
    @DeleteMapping("/delete/{classId}")
    @CacheEvict(value = "Category", allEntries = true)
    public R<String> delete(@PathVariable String classId) {
        LambdaQueryWrapper<Wares> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Wares::getCategoryId, classId);
        List<Wares> list = waresService.list(queryWrapper);
        if (ObjectUtils.isNotEmpty(list)) {
            return R.error("该类下存在商品，无法删除此分类");
        }
        boolean remove = categoryService.removeById(classId);
        return remove ? R.success("删除成功!") : R.error("删除失败,不存在该分类!");
    }

}
